package dp2.tablet.proyecto;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import dp2.tablet.proyecto.bean.*;
import dp2.tablet.proyecto.gestores.GestorCaja;
import dp2.tablet.proyecto.gestores.GestorEntrada;
import dp2.tablet.proyecto.gestores.GestorPuntoVenta;
import dp2.tablet.proyecto.gestores.GestorUsuarios;
import dp2.tablet.proyecto.util.JSONAbrirCaja;
import dp2.tablet.proyecto.util.JSONCajero;
import dp2.tablet.proyecto.util.JSONCanjearListener;
import dp2.tablet.proyecto.util.JSONLogin;
import dp2.tablet.proyecto.util.JSONLoginListener;
import dp2.tablet.proyecto.util.JSONReader;
import dp2.tablet.proyecto.util.JSONReaderInt;
import dp2.tablet.proyecto.util.JSONReaderIntListener;
import dp2.tablet.proyecto.util.JSONReaderListener;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class abrircaja  extends Activity implements JSONReaderListener,JSONReaderIntListener,JSONCanjearListener{
	GestorCaja dbCaja;	
	GestorPuntoVenta dbpto;
	private static CajaBean Caja;
	private static PuntoVentaBean ptoVenta;
	private List <CajaBean> cajas;
	private List <PuntoVentaBean>  ptos;
	private String StrCaja="si hay";
	private String StrPtoVenta="si hay";
	
	ProgressDialog myProgressDialog = null;
	int intContadorProgress=0;
	
		@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.abrir_caja);
	        
	        Bundle bundle=getIntent().getExtras();      
	         
	        TextView nombre=(TextView) findViewById(R.id.abrir_caja_txtv_vendedor);
	        nombre.setText(Login.getUsuario().getNombre()+" "+Login.getUsuario().getApePaterno()+" "+Login.getUsuario().getApeMaterno());
	        
	        //DESDE JSON
	         
	      
	        getCajas();
	        getPtosVenta();
	        llenarComboPtoVenta();
	      
	       
	        //CAJAS Y LOCALES HARDCODEADOS
	        /*dbCaja = new GestorCaja(this);
	        dbCaja.addCaja(new CajaBean("CAJA11","CERRADO","1"));
	        dbCaja.addCaja(new CajaBean("CAJA12","CERRADO","1"));
	        dbCaja.addCaja(new CajaBean("CAJA13","CERRADO","1"));
	        dbCaja.addCaja(new CajaBean("CAJA14","CERRADO","1"));
	        dbCaja.addCaja(new CajaBean("CAJA21","CERRADO","2"));
	        dbCaja.addCaja(new CajaBean("CAJA22","CERRADO","2"));
	        dbCaja.addCaja(new CajaBean("CAJA23","CERRADO","2"));
	        dbCaja.addCaja(new CajaBean("CAJA31","CERRADO","3"));
	        dbCaja.addCaja(new CajaBean("CAJA32","CERRADO","3"));
	        dbCaja.addCaja(new CajaBean("CAJA33","CERRADO","3"));
	        dbCaja.addCaja(new CajaBean("CAJA34","CERRADO","3"));
	        
	        dbpto = new GestorPuntoVenta(this);
	        dbpto.addPtoVenta(new PuntoVentaBean("1","001001","Wong - La Molina","0011","0011"));
	        dbpto.addPtoVenta(new PuntoVentaBean("2","001001","Plaza Vea - Surco","0011","0011"));
	        dbpto.addPtoVenta(new PuntoVentaBean("3","001001","Las Malvinas - Monterrico","0011","0011"));*/

		}
		 
		public void llenarCombo(String idpuntoventa){
			
		   //LinkedList <CajaBean> cajas = (LinkedList<CajaBean>) dbCaja.getAllCaja();
		   cajas = dbCaja.getAllCaja(idpuntoventa);
			Spinner caja =  (Spinner)findViewById(R.id.abriCaja_spinner_caja);
			
			if (cajas.size() == 0 ){
				ArrayAdapter<String> spinner_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new String[]{"Ninguno"});
				spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				caja.setAdapter(spinner_adapter);
			}
			else{
			ArrayAdapter<CajaBean> spinner_adapter = new ArrayAdapter<CajaBean>(this, android.R.layout.simple_spinner_item, cajas );
			//A�adimos el layout para el men� y se lo damos al spinner
			spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			caja.setAdapter(spinner_adapter);
			}
			
			caja.setOnItemSelectedListener(
	                new OnItemSelectedListener() {
	                    public void onItemSelected(
	                            AdapterView<?> parent, View view, int position, long id) {
	                    	//
	                    	if (cajas.size() != 0 ){
	                    		abrircaja.Caja = (CajaBean) parent.getItemAtPosition(position);
	                    		StrCaja = "si hay";
	                    	//TextView text = (TextView)findViewById(R.id.abrir_caja_txtv_vendedor);
	                    	//text.setText("--> " +alimentoId );
	                    	}else{
	                    		StrCaja = (String) parent.getItemAtPosition(position);
	                    	}
	                    }

	                    public void onNothingSelected(AdapterView<?> parent) {
	                        
	                    }
	                });
			//ArrayAdapter<ObjetosClase> spinner_adapter = new ArrayAdapter<ObjetosClase>(this, android.R.layout.simple_spinner_item, cajas);
			
		}
		public void llenarComboPtoVenta(){
			
			ptos = dbpto.getAllptos();
			Spinner ptosV =  (Spinner)findViewById(R.id.abrir_caja_sipinner_ptoVenta);
			
			if(ptos.size() == 0){
				ArrayAdapter<String> spinner_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new String[]{"Ninguno"});
				spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				ptosV.setAdapter(spinner_adapter);
			}else{
				ArrayAdapter<PuntoVentaBean> spinner_adapter = new ArrayAdapter<PuntoVentaBean>(this, android.R.layout.simple_spinner_item, ptos );
				spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				ptosV.setAdapter(spinner_adapter);	
				
			}
		
			ptosV.setOnItemSelectedListener(
	                new OnItemSelectedListener() {
	                    public void onItemSelected(
	                            AdapterView<?> parent, View view, int position, long id) {
	                    	//llenarCombo();
	                    	if ( ptos.size() !=0 ) {	
	                    	
	                    	String IdPtoVenta = ((PuntoVentaBean) parent.getItemAtPosition(position)).getIdpuntoventa();
	                    	llenarCombo(IdPtoVenta);
	                    	abrircaja.ptoVenta = (PuntoVentaBean) parent.getItemAtPosition(position);
	                    	StrPtoVenta = "Si hay";
	                    	//TextView text = (TextView)findViewById(R.id.abrir_caja_txtv_vendedor);
	                    	//text.setText("--> " +alimentoId );
	                    	}else{
	                    		StrPtoVenta = (String) parent.getItemAtPosition(position);
	                    	}
	                    }

	                    public void onNothingSelected(AdapterView<?> parent) {
	                        
	                    }
	                });
		
		}
		
		public void onAbrirClick (View botton) {  //throws IOException, JSONException
	    	
			
			if (isNetworkAvailable()==true){
			
				EditText  valor_soles = (EditText)findViewById(R.id.abrir_caja_edittxtf_mntoS);
			    EditText  valor_dolares = (EditText)findViewById(R.id.abrir_caja_edittxtf_mntoD);
			    Double  val_soles;
			    Double  val_dolares;
			    
			    try{
			    val_soles = Double.valueOf(valor_soles.getText().toString());
			    }catch (Exception e){
			    	val_soles = 0.0;
			    }
			    
			    try{
			    val_dolares = Double.valueOf(valor_dolares.getText().toString());
			    }catch (Exception e){
			    	val_dolares = 0.0;
			    }
				
			    
			    float fltTipoCambio=0;
				if(StrPtoVenta.equals("Ninguno")){
					Toast.makeText(this,"Debe selecccionar un Punto de Venta", Toast.LENGTH_SHORT).show();
				}else if (StrCaja.equals("Ninguno")){
					Toast.makeText(this,"Debe selecccionar una caja", Toast.LENGTH_SHORT).show();
				}else if (valor_soles.getText().toString().equals("") && valor_dolares.getText().toString().equals("")){
					Toast.makeText(this,"Debe registrar por lo menos monto", Toast.LENGTH_SHORT).show();
				}else if ((val_soles + val_dolares) <= 0.0 ){
					Toast.makeText(this,"Los valores ingresados debe ser mayor a 0", Toast.LENGTH_SHORT).show();
				}else if (estado_caja()== false){
					
					final Dialog dialog = new Dialog(this);
					dialog.setContentView(R.layout.dialog);
					dialog.setTitle("Caja Abierta");
					
					TextView text = (TextView) dialog.findViewById(R.id.text);
					text.setText("La caja que desea acceder ya se abierta, por favor regrese a la ventana anterior");
					Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK); 
					dialogButton.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							/*Intent intent= new Intent();
							intent.setClass(getParent(), Login.class);
				    		startActivity(intent);*/
							dialog.dismiss();
						}
					});
					
					Button dialogButton2 = (Button) dialog.findViewById(R.id.dialogButtonCancelar);
					dialogButton2.setVisibility(View.GONE);
					
					//Layout lay =  (Layout) dialog.findViewById(R.id.dialog_layout);
					//ImageView image = (ImageView) dialog.findViewById(R.id.image);
					//image.setImageResource(R.drawable.mal);
					dialog.show();
					
					
				}else if((fltTipoCambio=GestorEntrada.consultarTC(this))<0){
					Toast.makeText(this,"No se ha registrado tipo de cambio", Toast.LENGTH_SHORT).show();
				}
				else{
					
					InsertarenBD();
					CambiarEstado();
					Intent intent= new Intent();
	    			intent.setClass(this, Principal.class);
	    			startActivity(intent);
					
					Principal.tipoCambio=fltTipoCambio;
					Principal.abriCaja=this;
				}
			}else{
				
				Toast.makeText(this,"Problema de conexion", Toast.LENGTH_SHORT).show();
			}
			
	    }
		
		private boolean estado_caja(){
			
			int intJSONEstadoCaja;
	    	try {
				JSONReaderInt reader = new JSONReaderInt();
				reader.setJSONReaderIntListener((JSONReaderIntListener)this);
				intJSONEstadoCaja=(reader.execute("http://200.16.7.112:3000/sales_management/sales_points/dameEstadoCaja/"+abrircaja.getCaja().getId()+".json")).get();
			}  catch (Throwable t) {
	  			Toast.makeText(this, "Request failed webser_vice_pto_Venta_validos" + t.toString(),
						Toast.LENGTH_LONG).show();
	  			return false;
			} 		
			
	    	if (intJSONEstadoCaja==3){
	    		return false;    		
	    	}
	    	else    	
	    		return true;
			
			
		}
		
		
		public void InsertarenBD(){
			
			EditText  valor_soles = (EditText)findViewById(R.id.abrir_caja_edittxtf_mntoS);
		    EditText  valor_dolares = (EditText)findViewById(R.id.abrir_caja_edittxtf_mntoD);
		    
		    Double val_sol;
		    Double val_dol;
		    
		    try{ val_sol = Double.parseDouble(valor_soles.getText().toString()); }
			catch(NumberFormatException e){ val_sol = 0.0; }
		    
		    try{ val_dol = Double.parseDouble(valor_dolares.getText().toString())*2.68; }
			catch(NumberFormatException e){ val_dol = 0.0; }
			
			
			try {
				
				 new JSONAbrirCaja().execute("http://200.16.7.112:3000/sales_management/cashiers/create_operations_cashier/",valor_soles.getText().toString(), valor_dolares.getText().toString());
			   
			}catch (Throwable t) {
	  			Toast.makeText(this, "Request failed: " + t.toString(),
						Toast.LENGTH_LONG).show();
			} 
			
		
		}
		
		
		public void CambiarEstado(){
				try {
					
					 new JSONCajero().execute("http://200.16.7.112:3000/sales_management/cashiers/update_cashier","3");
				   
				}catch (Throwable t) {
		  			Toast.makeText(this, "Request failed: " + t.toString(),
							Toast.LENGTH_LONG).show();
				} 
		
		}
		
		private void getCajas(){
			JSONArray jCajas;
			try {
				JSONReader reader = new JSONReader();
				reader.setJSONReaderListener((JSONReaderListener)this);
				jCajas=(reader.execute("http://200.16.7.112:3000/sales_management/sales_points/dameCajas/dameCajas.json")).get();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
				return;
			} catch (ExecutionException e1) {
				e1.printStackTrace();
				return;
			}

			//List<UsuarioBean> lstUsuarios= new ArrayList<UsuarioBean>();
			dbCaja = new GestorCaja(this);  //INICIALIZO EL GESTOR CAJAS
			try{
				for(int i=0;i < jCajas.length();i++){

					dbCaja.addCaja(new CajaBean(jCajas.getJSONObject(i).getJSONObject("cashier").getInt("id"),jCajas.getJSONObject(i).getJSONObject("cashier").getString("descripcion"),jCajas.getJSONObject(i).getJSONObject("cashier").getInt("cashier_state_id"),jCajas.getJSONObject(i).getJSONObject("cashier").getInt("sales_point_id")));
					//Toast.makeText(this, " ID "+String.valueOf(jCajas.getJSONObject(i).getJSONObject("cashier").getInt("cashier_state_id")), Toast.LENGTH_LONG).show();
			    }			
			}catch(JSONException e){
				Log.e("log_tag", "Error parsing data "+e.toString());
		    }
			int j=0;
			j+=1;
		}
		
		
		private void getPtosVenta(){
			JSONArray jPtosVentas = null;
			JSONArray IdPtosValidos = null;
			
			try {
				JSONReader reader = new JSONReader();
				reader.setJSONReaderListener((JSONReaderListener)this);
				
				jPtosVentas=(reader.execute("http://200.16.7.112:3000/sales_management/sales_points/damePuntosDeVenta/damePuntosDeVenta.json")).get();
				
			} catch (Throwable t) {
	  			Toast.makeText(this, "Request failed ptos venta todos" + t.toString(),
						Toast.LENGTH_LONG).show();
			} 
			
			
			try {
				JSONReader reader2 = new JSONReader();
				reader2.setJSONReaderListener((JSONReaderListener)this);
				
				IdPtosValidos=(reader2.execute("http://200.16.7.112:3000/sales_management/sales_points/dameCajasAsignadas/"+Integer.valueOf(Login.getUsuario().getId())+".json")).get(); //Integer.valueOf(Login.getUsuario().getId())

			} catch (Throwable t) {
	  			Toast.makeText(this, "Request failed webser_vice_pto_Venta_validos" + t.toString(),
						Toast.LENGTH_LONG).show();
			} 
			
			
			
			//List<UsuarioBean> lstUsuarios= new ArrayList<UsuarioBean>();
			
			 dbpto = new GestorPuntoVenta(this); // INICIALIZA EL GESTRO PTOS DE VENTA
			
			 try{
					for(int i=0;i < jPtosVentas.length();i++){

						dbpto.addPtoVenta(new PuntoVentaBean(String.valueOf(jPtosVentas.getJSONObject(i).getJSONObject("sales_point").getInt("id")),jPtosVentas.getJSONObject(i).getJSONObject("sales_point").getString("address"),
								jPtosVentas.getJSONObject(i).getJSONObject("sales_point").getString("descripcion"),"0011","0011"));
						//Toast.makeText(this, jPtosVentas.getJSONObject(i).getJSONObject("sales_point").getString("descripcion") + " ID "+String.valueOf(jPtosVentas.getJSONObject(i).getJSONObject("sales_point").getInt("id")), Toast.LENGTH_LONG).show();
				    }			
				}catch (Throwable t) {
		  			Toast.makeText(this, "Request failed PTOS_VENTA: " + t.toString(),
							Toast.LENGTH_LONG).show();
				} 
			 
			 try{
				 
				// Toast.makeText(this,IdPtosValidos.toString(), Toast.LENGTH_LONG).show();
				 
					for(int i=0;i < IdPtosValidos.length();i++){
						
						
						dbpto.addPtoVentaValidos(IdPtosValidos.getJSONObject(i).getJSONObject("sales_points_worker").getInt("sales_point_id"),IdPtosValidos.getJSONObject(i).getJSONObject("sales_points_worker").getInt("estado"));
						
						
				    }			
				}catch (Throwable t) {
		  			Toast.makeText(this, "Request failed PTOSVALIDOS: " + t.toString() + " CANTIDAD "+IdPtosValidos.length(),
							Toast.LENGTH_LONG).show();

				} 

		}
		
		
		public static PuntoVentaBean ptoVenta() {
			return ptoVenta;
		}

		public static CajaBean getCaja() {
			return Caja;
		}
		
		
		
		
		@Override
		public void onConnected() {
			// TODO Auto-generated method stub
			intContadorProgress++;
			if (intContadorProgress==1){
				myProgressDialog = ProgressDialog.show(this, "Cargando...", "Por favor esperar...", true);
				
			}
		}

		@Override
		public void onSent() {
			// TODO Auto-generated method stub
			
		}


		@Override
		public void onFinished(JSONArray jArray) {
			// TODO Auto-generated method stub
			intContadorProgress--;
			if (intContadorProgress==0)
				myProgressDialog.dismiss();
		}

		@Override
		public void onFinished(Integer id) {
			// TODO Auto-generated method stub
			intContadorProgress--;
			if (intContadorProgress==0)
				myProgressDialog.dismiss();		
		}
		
		private boolean isNetworkAvailable() {
	        ConnectivityManager connectivityManager 
	              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo activeNetworkInfo= connectivityManager.getActiveNetworkInfo();
	        return activeNetworkInfo != null;
	    }
}
